<template>
  <view class="consignment-page">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-content">
        <view class="navbar-left" @click="goBack">
          <image class="back-icon" src="/static/Images/goods/Fanhui.png" mode="aspectFit"></image>
        </view>
        <view class="navbar-title">卡密回收</view>
        <view class="navbar-right"></view>
      </view>
    </view>

    <!-- 页面内容 -->
    <view class="page-content">
      <!-- 分类标签 -->
      <!-- 分类区域父容器 -->
      <view class="category-section">
        <scroll-view class="category-tabs-container" scroll-x="true" show-scrollbar="false">
          <view class="category-tabs">
            <view 
              v-for="(category, index) in categories" 
              :key="index"
              class="category-tab"
              :class="{ active: activeCategory === index }"
              @click="selectCategory(index)"
            >
              {{ category.name }}
            </view>
          </view>
        </scroll-view>

        <!-- 分类圆圈图标区域 -->
        <scroll-view v-if="!isExpanded" class="category-circles-scroll" scroll-x="true" show-scrollbar="false">
          <view class="category-circles">
            <view 
              v-for="(item, index) in categoryItems" 
              :key="index"
              class="category-circle"
              :class="{ active: activeCategoryItem === index }"
              @click="selectCategoryItem(index)"
            >
              <view class="circle-icon">
                <image v-if="item.icon" :src="item.icon" class="icon-image" mode="aspectFit" />
              </view>
              <text class="circle-label">{{ item.label }}</text>
            </view>
          </view>
        </scroll-view>
        <view v-else class="category-circles-expanded">
          <view 
            v-for="(item, index) in categoryItems" 
            :key="index"
            class="category-circle"
            :class="{ active: activeCategoryItem === index }"
            @click="selectCategoryItem(index)"
          >
            <view class="circle-icon">
              <image v-if="item.icon" :src="item.icon" class="icon-image" mode="aspectFit" />
            </view>
            <text class="circle-label">{{ item.label }}</text>
          </view>
        </view>

        <!-- 点击展开按钮 -->
        <view class="expand-section" @click="toggleExpand">
          <text class="expand-text">点击展开</text>
          <text class="expand-icon" :class="{ rotated: isExpanded }">V</text>
        </view>
      </view>

      <!-- 商品列表 -->
      <view class="goods-list">
        <!-- 加载状态 -->
        <view v-if="loading" class="loading-container">
          <view class="loading-text">数据加载中...</view>
        </view>
        
        <!-- 商品列表内容 -->
        <view 
          v-else
          v-for="(item, index) in goodsList" 
          :key="index"
          class="goods-item"
        >
          <!-- 商品缩略图 -->
          <view class="goods-thumbnail">
            <image 
              :src="(Array.isArray(item.imgs) ? item.imgs[0] : item.imgs) || '/static/images/default-product.png'" 
              class="thumbnail-image"
              mode="aspectFill"
            />
          </view>
          
          <!-- 右侧内容区 -->
          <view class="goods-content">
            <!-- 第一行：商品名称 -->
            <view class="goods-title">{{ item.goods_name }}</view>
            
            <!-- 第二行：商品编号 -->
            <view class="goods-code">商品编号：{{ item.id }}</view>
            
            <!-- 第三行：价格、库存、按钮 -->
            <view class="goods-actions">
              <view class="goods-price">¥{{ item.price }}</view>
              <view class="goods-status" @click="launchCard(item)">
                {{ item.num >= 100 ? '已爆满' : `可上架${item.num}张` }}
              </view>
              <!-- <button class="action-btn" @click="launchCard(item)" :class="{ 'btn-disabled': item.num >= 100 }" :disabled="item.num >= 100">
                上架
              </button> -->
              <button class="action-btn" @click="extractCard(item)">
                提交卡密
              </button>
            </view>
          </view>
        </view>
        
        <!-- 空数据状态 -->
        <view v-if="!loading && goodsList.length === 0" class="empty-container">
          <view class="empty-text">暂无商品数据</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { goodsApi } from '@/utils/api'

export default {
  name: 'Consignment',
  data() {
    return {
      activeCategory: 0,
      activeCategoryItem: 0,
      isExpanded: false,
      categories: [],
      categoryItems: [],
      goodsList: [],
      loading: false
    }
  },
  async onLoad() {
    await this.loadCategoryData()
    // 加载第一个分类的子分类
    if (this.categories.length > 0) {
      await this.loadSubCategories(this.categories[0].id)
      // 加载第一个子分类的商品数据
      if (this.categoryItems.length > 0) {
        await this.loadGoodsList(this.categoryItems[0].id)
      }
    }
  },
  methods: {
    goBack() {
      uni.navigateBack()
    },
    async selectCategory(index) {
      this.activeCategory = index
      this.activeCategoryItem = 0
      await this.loadCategoryData(this.categories[index].id)
      await this.loadSubCategories(this.categories[index].id)
      // 自动加载第一个子分类的商品
      if (this.categoryItems.length > 0) {
        await this.loadGoodsList(this.categoryItems[0].id)
      }
    },
    async selectCategoryItem(index) {
      this.activeCategoryItem = index
      await this.loadGoodsList(this.categoryItems[index].id)
    },
    toggleExpand() {
      this.isExpanded = !this.isExpanded
    },
    extractCard(item) {
      uni.navigateTo({
        url: `/pages/tasks/addkey?id=${item.id}`
      })
    },
    launchCard(item) {
      if (item.num >= 100) {
        uni.showToast({
          title: '库存已爆满，无法上架',
          icon: 'none'
        })
        return
      }
      uni.navigateTo({
        url: `/pages/tasks/addkey?id=${item.id}`
      })
    },
      async loadSubCategories(parentId) {
        try {
          const response = await goodsApi.getGoodsClass()
          if (response && response.data) {
            // 过滤pid等于选中分类ID的子分类
            const subCategories = response.data.filter(item => 
              item.pid === parentId && item.type === 2
            )
            // 将子分类数据映射到categoryItems
            this.categoryItems = subCategories.map(item => ({
              id: item.id,
              label: item.name,
              icon: item.icon || '', // 如果有图标字段的话
              data: item
            }))
            console.log('加载子分类数据成功:', subCategories)
          }
        } catch (error) {
          console.error('加载子分类数据失败:', error)
          this.categoryItems = [] // 失败时清空
        }
      },
      async loadGoodsList(classId) {
          try {
            this.loading = true
          const params = {
            class_id: classId,
            type: 2,
            page: 1,
            size: 10
          }
          const response = await goodsApi.getGoodsList(params)
          if (response && response.data) {
            this.goodsList = response.data
          } else {
            this.goodsList = []
          }
        } catch (error) {
          console.error('加载商品列表失败:', error)
          this.goodsList = []
        } finally {
          this.loading = false
        }
      },
      async loadCategoryData(categoryId) {
      try {
        const response = await goodsApi.getGoodsClass()
        if (response && response.data) {
          // 过滤pid不为0且type为2的分类
          const filteredCategories = response.data.filter(item => 
            item.pid === 0 
          )
          this.categories = filteredCategories
          console.log('加载分类数据成功:', filteredCategories)
        }
      } catch (error) {
        console.error('加载分类数据失败:', error)
        uni.showToast({
          title: '加载分类失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style scoped>
.consignment-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.custom-navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background: #FEF1F1;
  padding-top: var(--status-bar-height, 44px);
}

.navbar-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 44px;
  padding: 0 16px;
}

.navbar-left {
  width: 44px;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 24px;
  height: 24px;
  font-weight: bold;
}

.navbar-title {
  flex: 1;
  text-align: center;
  font-size: 18px;
  font-weight: 600;
  color: #111;
}

.navbar-right {
  width: 44px;
}

.page-content {
  padding-top: calc(var(--status-bar-height, 44px) + 44px);
  padding: calc(var(--status-bar-height, 44px) + 44px) 16px 16px;
}

.category-section {
  background: #FEF1F1;
  padding: 16px;
  margin-bottom: 16px;
  margin-left: -1rem;
   width: 100%;
 }
 
 .category-tabs-container {
   white-space: nowrap;
   margin-bottom: 16px;
 }
 
 /* 隐藏滚动条的通用样式 */
  .category-tabs-container,
  .category-circles-scroll {
    scrollbar-width: none; /* Firefox */
    -ms-overflow-style: none; /* IE 10+ */
  }
  
  .category-tabs-container::-webkit-scrollbar,
  .category-circles-scroll::-webkit-scrollbar {
    display: none; /* Chrome Safari */
    width: 0;
    height: 0;
  }

.category-tabs {
  display: inline-flex;
  border-radius: 8px;
  padding: 4px;
  min-width: 100%;
  margin-bottom: 0.5rem;
}

.category-tab {
  flex-shrink: 0;
  text-align: center;
  padding: 4px 14px;
  border-radius: 20px;
  font-size: 14px;
  color: #666666;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.category-tab.active {
  background-color: #FF3037;
  color: #ffffff;
  font-weight: 600;
}

.category-circles-scroll {
  margin-bottom: 20px;
}

.category-circles {
  display: flex;
  gap: 20px;
  padding: 0 20px;
  white-space: nowrap;
  margin-bottom: 0.5rem;
}

.category-circles-expanded {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  padding: 0 20px;
  margin-bottom: 20px;
}

.category-circles-expanded .category-circle {
  width: calc(25% - 15px);
  min-width: 60px;
}

.category-circle {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
}

.circle-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: #e0e0e0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.category-circle.active .circle-icon {
  border-color: #ff6b6b;
  background-color: #fff5f5;
}

.icon-image {
  width: 36px;
  height: 36px;
  border-radius: 50%;
}

.circle-label {
  font-size: 12px;
  color: #666666;
  text-align: center;
  padding: 4px 14px;
  border-radius: 20px;
  transition: all 0.3s ease;
  white-space: nowrap;
  background-color: transparent;
}

.category-circle.active .circle-label {
  background-color: #FF3037;
  color: #ffffff;
  font-weight: 600;
}

.expand-section {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12px;
  margin-bottom: 16px;
  cursor: pointer;
}

.expand-text {
  font-size: 14px;
  color: #666666;
  margin-right: 8px;
}

.expand-icon {
  font-size: 12px;
  color: #666666;
  transition: transform 0.3s ease;
  margin-left: -0.4rem;
}

.expand-icon.rotated {
  transform: rotate(180deg);
  margin-left: -0.4rem;
}

.goods-list {
  background-color: #ffffff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  margin: 0 4px;
}

.goods-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f5f5f5;
  transition: background-color 0.2s ease;
}

.goods-item:last-child {
  border-bottom: none;
}

.goods-item:active {
  background-color: #f8f9fa;
}

/* 商品缩略图 */
.goods-thumbnail {
  width: 80px;
  height: 80px;
  margin-right: 12px;
  border-radius: 8px;
  overflow: hidden;
  background-color: #f5f5f5;
}

.thumbnail-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 右侧内容区域 */
.goods-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.goods-title {
  font-size: 15px;
  color: #333333;
  font-weight: 500;
  line-height: 1.3;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.goods-code {
  font-size: 12px;
  color: #999999;
}

.goods-price {
  font-size: 12px;
  color: #FF3037;
  font-weight: 600;
}

/* 第三行操作区域 */
.goods-actions {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 12px;
  margin-top: 4px;
}

.goods-actions .goods-price {
  font-size: 16px;
  color: #FF3037;
  font-weight: 600;
  flex: 1;
  min-width: 60px;
}

.goods-status {
  font-size: 12px;
  color: #666666;
  background-color: #f5f5f5;
  border-radius: 12px;
  text-align: center;
  min-width: 65px;
  flex: 1;
}

.goods-status.status-disabled {
  background-color: #e8e8e8;
  color: #999999;
}

.action-btn {
  background-color: #FF3037;
  color: #ffffff;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  text-align: center;
  min-width: 60px;
  flex: 1;
  border: none;
  outline: none;
}

.action-btn:active {
  background-color: #e02028;
  transform: scale(0.95);
}

.action-btn.btn-disabled {
  background-color: #e8e8e8;
  color: #999999;
  cursor: not-allowed;
}

.action-btn.btn-disabled:active {
  background-color: #e8e8e8;
  transform: none;
}

/* 加载状态 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 60px 20px;
}

.loading-text {
  font-size: 14px;
  color: #999999;
}

/* 空数据状态 */
.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 60px 20px;
}

.empty-text {
  font-size: 14px;
  color: #999999;
}
</style>